package com.hzhr.iot.collect.protocol.encipher;

import com.hzhr.iot.collect.constant.UpDownEnum;
import com.hzhr.iot.collect.constant.entity.MessagefieldEntity;
import com.hzhr.iot.collect.constant.entity.MessagetmpEntity;
import com.hzhr.iot.collect.constant.entity.constant.MessagefieldEntityConstant;
import com.hzhr.iot.collect.constant.entity.constant.MessagetmpEntityConstant;
import com.hzhr.iot.collect.util.StrUtil;
import org.springframework.stereotype.Component;

@Component
public class Encipher1 implements Encipher {
    @Override
    public String encrypt(String message, int protocolId, String deviceId, UpDownEnum upDownFlag) {
        MessagetmpEntity messagetmpEntity = MessagetmpEntityConstant.getMessagetmpEntityByProtocolId(protocolId);

        //加密目标字节
        if (messagetmpEntity.getEncryptedbytefieldId() != null) {
            //获取加密字节
            Integer encryptedByteFieldId = messagetmpEntity.getEncryptedbytefieldId();
            MessagefieldEntity encryptedByteFieldEntity = MessagefieldEntityConstant.MAP.get(encryptedByteFieldId);
            Integer fieldStartIndex = (encryptedByteFieldEntity.getStartindex() * 2 + message.length()) % message.length();
            Integer fieldSize = encryptedByteFieldEntity.getSize() * 2;
            String encryptedByte = StrUtil.substringBySize(message, fieldStartIndex, fieldSize);//加密字节
            Integer targetByteStartIndex = 10;//目标字节起始位置
            Integer targetByteEndIndex = message.length() - 8;//目标字节结束位置
            String targetByte = StrUtil.substring(message, targetByteStartIndex, targetByteEndIndex);

            //加密
            byte[] targetBs = StrUtil.hexStr2byte(targetByte);
            byte[] encryptedBs = StrUtil.hexStr2byte(encryptedByte);
            byte encryptedB = encryptedBs[0];
            byte[] oriBs = new byte[targetBs.length];
            for (int i = 0; i < targetBs.length; i++) {
                byte targetB = targetBs[i];
                targetB ^= encryptedB;
                oriBs[i] = targetB;
            }
            String oriByte = StrUtil.byte2hexStr(oriBs);//原始字节(解密后的字节)

            StringBuilder oriMessageSb = new StringBuilder(message);
            oriMessageSb.replace(targetByteStartIndex, targetByteEndIndex,
                    oriByte);
            message = oriMessageSb.toString();
        }

        return message;
    }
}
